package utils;

/**
 * Author: yangzhi@djcars.cn
 * Create: 2012-07-11 14:08
 */

import play.data.Upload;
import play.data.validation.Error;
import play.data.validation.Validation;
import play.mvc.Http;
import play.mvc.Http.Request;
import play.mvc.Router;
import play.mvc.results.RenderJson;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.List;

public class RequestHelper {

    public static class ValidationError {

        public ValidationError(List<Error> errors) {
            this.errors = errors;
        }

        public List<Error> errors;
    }

    /**
     * 如果有校验错误，则输出错误，否则不处理
     */
    public static void checkValidation() {
        if (Validation.hasErrors()) {
            Http.Response response = Http.Response.current();
            response.setContentTypeIfNotSet("text/html");
            throw new RenderJson(new ValidationError(Validation.errors()));
        }
    }

    /**
     * 获取参数
     *
     * @param key 参数名称
     * @param length 最大长度，如果提交的参数值的长度超出此值(大于0)，则将截断
     */
    public static String getParam(String key, int length) {
        String value = Request.current().params.get(key);
        if (StringUtils.isNotEmpty(value) && length > 0 && value.length() > length) {
            return value.substring(0, length);
        } else {
            return value;
        }
    }

    /**
     * 获取参数的值，并转为int类型返回
     *
     * @param key 参数名称
     */
    public static int getIntParam(String key) {
        String value = Request.current().params.get(key);
        if (StringUtils.isEmpty(value)) {
            return 0;
        }

        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException ex) {
            return 0;
        }
    }

    public static double getDoubleParam(String key) {
        String value = Request.current().params.get(key);
        if (StringUtils.isEmpty(value)) {
            return 0;
        }

        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException ex) {
            return 0;
        }
    }

    public static long getLongParam(String key) {
        String value = Request.current().params.get(key);
        if (StringUtils.isEmpty(value)) {
            return 0L;
        }

        try {
            return Long.parseLong(value);
        } catch (NumberFormatException ex) {
            return 0L;
        }
    }

    public static int getIntParamByCheckBox(String key) {
        String value = Request.current().params.get(key);
        if (StringUtils.isEmpty(value)) {
            return 0;
        }

        try {
            if (value.equals("on")){
                return  1;
            }else {
                return 0;
            }
        } catch (NumberFormatException ex) {
            return 0;
        }
    }

    /**
     * 获取参数
     *
     * @param key 参数名称
     * @param length 最大长度，如果提交的参数值的长度超出此值(大于0)，则将截断
     */
    public static String getParam(String key, int length,Boolean searchKey) {
        String value = "";
        if (searchKey){
            value = Request.current().params.get("key["+key+"]");
        }else{
            value = Request.current().params.get(key);
        }
        if (StringUtils.isNotEmpty(value) && length > 0 && value.length() > length) {
            return value.substring(0, length);
        } else {
            return value;
        }
    }

    /**
     * 获取参数的值，并转为int类型返回
     *
     * @param key 参数名称
     */
    public static int getIntParam(String key,Boolean searchKey) {
        String value = "";
        if (searchKey){
            value = Request.current().params.get("key["+key+"]");
        }else{
            value = Request.current().params.get(key);
        }

        if (StringUtils.isEmpty(value)) {
            return 0;
        }

        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException ex) {
            return 0;
        }
    }

    public static  String getSearchParam(String key,Boolean searchKey){
        String value = "";
        if (searchKey){
            value = Request.current().params.get("key["+key+"]");
        }else{
            value = Request.current().params.get(key);
        }
        return value;
    }

    /**
     * 获取上传的文件对象
     *
     * @param key 参数名称
     */
    public static File getFile(String key) {
        //简单方式
        return Request.current().params.get(key, File.class);

    }


    /**
     * 获取客户端的IP地址
     * @return
     */
    public static String getRemoteAddress(){
        return Request.current().remoteAddress;
    }

    public static Boolean isAjaxQequest(){
        Boolean  result = false;
        Http.Header xRequestedWith = Request.current().headers.get("x-requested-with");
        if (xRequestedWith!=null) {
            if (xRequestedWith.value().equals("XMLHttpRequest")) {
                result = true;
            }
        }
       return result;
    }

    /**
     * 获取来源页面地址
     *
     * @param replacement 如果没有来源页面则返回此替代地址
     */
    public static String getReferer(String replacement) {
        String refer = getParam("referer", 0);
        if(!Utils.isNullOrEmpty(refer)){
            return refer;
        }
        Http.Header referer = Request.current().headers.get("referer");
        replacement = getRouterUrl(replacement);

        if (referer == null) {
            return replacement;
        }
        String refererUrl = referer.value();
        //如果来源页面为空或者来自菜单页，则返回替代地址
        if (Utils.isNullOrEmpty(refererUrl)
                || StringUtils.endsWithIgnoreCase(refererUrl, "/menu")
                || StringUtils.endsWithIgnoreCase(refererUrl, "/main")) {
            return replacement;
        } else {
            return refererUrl;
        }
    }

    /**
     * 获取某个路由的地址
     *
     * @param routerAction 路由的动作，类似：@{Controller.action()}
     */
    public static String getRouterUrl(String routerAction) {
        if (!Utils.isNullOrEmpty(routerAction)
                && routerAction.startsWith("@")) {
            int pos = routerAction.indexOf("}");
            if (pos != -1) {
                String action = null;
                String appendStr = null;
                Boolean abs = false;
                if (routerAction.startsWith("@{")) {
                    action = routerAction.substring(2, pos);
                } else if (routerAction.startsWith("@@{")) {
                    abs = true;
                    action = routerAction.substring(3, pos);
                }
                if (action != null && action.length() > 0) {
                    action = action.replaceAll("\\(\\s*\\)$", "");
                    if (action.length() > 0) {
                        Router.ActionDefinition def = Router.reverse(action);
                        if (def != null) {
                            if (abs) {
                                def.absolute();
                            }
                            appendStr = routerAction.substring(pos + 1);
                            routerAction = def.toString().concat(appendStr);
                        }
                    }
                }
            }
        }
        return routerAction;
    }

}